package com.seuic.hnjiningposapp.hnapps.ui.activity;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.cardview.widget.CardView;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.identity.Shell;
import com.identity.globalEnum;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.orhanobut.logger.Logger;
import com.seuic.hnjiningposapp.R;
import com.seuic.hnjiningposapp.hnapps.base.BaseActivity;
import com.seuic.hnjiningposapp.hnapps.bean.BankDataBean;
import com.seuic.hnjiningposapp.hnapps.bean.UserAccBean;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.BrushtheIdentityPp;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.ChangePsSuccessPp;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.DealingPopup;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.ErrorPopup;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.IdInfoPp;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.InputIdNumNamePp;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.InputNewPasswordPopup;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.InputPasswordPopup;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.LossPp;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.LossSuccesPp;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.PrintingPopup;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.ReadCardPopup;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.SelGetNumPp;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.SellOSSuccessPp;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.SellossOfPp;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.SureIdInfoPp;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.SurePrintPopup;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.VerifyCardPopup;
import com.seuic.hnjiningposapp.hnapps.util.HttpUtils;
import com.seuic.hnjiningposapp.hnapps.util.HttpUtilsV2;
import com.seuic.hnjiningposapp.hnapps.util.PrintUtil;
import com.seuic.hnjiningposapp.hnapps.util.TimeUtils;
import com.seuic.hnjiningposapp.hnapps.util.UiTool;
import com.seuic.posdsdk.pos_func.PosFuncs;
import com.socks.library.KLog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 特殊业务
 */
public class SpecialBusinessActivity extends BaseActivity implements SellOSSuccessPp.SuccessPpCallbACK, SellossOfPp.SellCallBack, SureIdInfoPp.sureidinfoCall, InputNewPasswordPopup.newpassWrodCallBack, ErrorPopup.OnFinishCallbacked, SurePrintPopup.ClickCallback, ChangePsSuccessPp.OnChangePw, InputIdNumNamePp
        .InputIdNumNameCallBack, LossSuccesPp.LossSuccessCallBack, InputPasswordPopup.ClickCallback, LossPp.LossPpCallBack, SelGetNumPp.SelGetNumTypeCallBack, IdInfoPp.OnSureIdInfo {
    //口头挂失方式
    public static final String READGET = "READ";
    public static final String HEADERGET = "HEADER";
    //操作类型 本activity
    private String MAKE_TYPE = "";
    //选择了核查业务
    private final String CHEACK = "CHEACK";
    //选择了挂失业务
    private final String LOSSOF = "LOSSOF";
    private final String CHANGE_PS = "CHANGE_PS";


    boolean bStop = false;
    private static final int REQUEST_ENABLE_BT = 2;
    private boolean bConnected = false;
    private int m_sec1, m_sec2;
    private int m_msec1, m_msec2;
    private Calendar c;
    private BluetoothDevice mDevice = null;
    private BluetoothAdapter mAdapter;
    private Shell shell = null;
    @BindView(R.id.networking_verification_btn)
    Button networkingVerificationBtn;
    @BindView(R.id.oralreportthe_lossof_btn)
    Button oralreporttheLossofBtn;
    @BindView(R.id.change_password_btn)
    Button changePasswordBtn;
    @BindView(R.id.local_layout)
    CardView localLayout;
    private BrushtheIdentityPp brushtheIdentityPp;
    private BasePopupView brushtheIdentityPpView;
    //读取的身份证姓名
    private String sf_name;
    //读取的身份证号码
    private String sf_num;
    private String packageName;
    private DealingPopup dealingPopup;
    private BasePopupView dealingPopupView;
    private IdInfoPp idInfoPp;
    private BasePopupView idInfoPpView;
    private SelGetNumPp selGetNumPp;
    private BasePopupView selGetNumPpView;
    private LossPp lossPp;
    private BasePopupView lossPpView;
    private InputPasswordPopup inputpasswordPop;
    private BasePopupView inputpasswordPopupView;
    private LossSuccesPp lossSuccesPp;
    private BasePopupView lossSuccesPpView;
    private InputIdNumNamePp inputIdNumNamePp;
    private BasePopupView inputIdNumNamePpView;
    private ReadCardPopup readcardPop;
    private BasePopupView readcardPopupView;
    private VerifyCardPopup verifycardPop;
    private BasePopupView verifycardPopupView;

    private ChangePsSuccessPp changePsSuccessPp;
    private BasePopupView changePsSuccessPpView;
    private SurePrintPopup surePrintPop;
    private BasePopupView surePrintPopupView;
    private PrintingPopup printingPop;
    private BasePopupView printingPopupView;
    private String cipassword;
    private String card_num;
    private String track2Data;
    private ErrorPopup errorPopup;
    private BasePopupView errorPopupPpView;
    private InputNewPasswordPopup inputNewPasswordPopup;
    private BasePopupView inputNewPasswordPopupView;
    private String card_username;
    private String make_time;
    private String mServerSeqNo;
    private SureIdInfoPp sureIdInfoPp;
    private BasePopupView sureIdInfoPpView;
    private String userid;
    private String username;
    private List<UserAccBean> userAccBeans;
    private SellossOfPp sellossOfPp;
    private BasePopupView sellossOfPpView;
    //确定挂失账的信息
    private UserAccBean mUserAccBean;
    //挂失的时候身份证号
    private String identityCard;
    private SellOSSuccessPp sellOSSuccessPp;
    private BasePopupView sellOSSuccessPpView;
    private String idusername;

    @Override
    public int initView(Bundle savedInstanceState) {
        return R.layout.activity_special_business;
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        setTitleText("特殊业务");
        findViewById(R.id.base_back_btn).setVisibility(View.INVISIBLE);
        sellOSSuccessPp = new SellOSSuccessPp(this, this);
        sellOSSuccessPpView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(sellOSSuccessPp);
        sellossOfPp = new SellossOfPp(this, this);
        sellossOfPpView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(sellossOfPp);
        sureIdInfoPp = new SureIdInfoPp(this, this);
        sureIdInfoPpView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(sureIdInfoPp);

        inputNewPasswordPopup = new InputNewPasswordPopup(this, this);
        inputNewPasswordPopupView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(inputNewPasswordPopup);


        errorPopup = new ErrorPopup(this, this);
        errorPopupPpView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(errorPopup);


        packageName = this.getPackageName();
        readcardPop = new ReadCardPopup(this);
        //打印纸是否正常界面
        surePrintPop = new SurePrintPopup(this, this, this);
        surePrintPopupView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(surePrintPop);
        printingPop = new PrintingPopup(this, this);
        //打印中界面
        printingPopupView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(printingPop);
        //验证账户信息界面
        changePsSuccessPp = new ChangePsSuccessPp(this, this);
        changePsSuccessPpView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(changePsSuccessPp);

        readcardPopupView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(readcardPop);
        verifycardPop = new VerifyCardPopup(this, this);
        //验证账户信息界面
        verifycardPopupView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(verifycardPop);
        inputIdNumNamePp = new InputIdNumNamePp(this, this);
        inputIdNumNamePpView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(inputIdNumNamePp);
        lossSuccesPp = new LossSuccesPp(this, this);
        lossSuccesPpView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(lossSuccesPp);
        inputpasswordPop = new InputPasswordPopup(this, this);
        //输入密码界面
        inputpasswordPopupView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(inputpasswordPop);
        lossPp = new LossPp(this, this);
        //选择挂失账户
        lossPpView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(lossPp);
        brushtheIdentityPp = new BrushtheIdentityPp(this);
        brushtheIdentityPpView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(brushtheIdentityPp);//身份证
        dealingPopup = new DealingPopup(this, this);
        //交易中
        dealingPopupView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(dealingPopup);

        idInfoPp = new IdInfoPp(this, this);
        idInfoPpView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(idInfoPp);//确定联网核查信息
        selGetNumPp = new SelGetNumPp(this, this);
        selGetNumPpView = new XPopup.Builder(this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                .asCustom(selGetNumPp);
    }

    @Override
    public void initEvent(Bundle savedInstanceState) {

    }


    @OnClick({R.id.networking_verification_btn, R.id.oralreportthe_lossof_btn, R.id.change_password_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.networking_verification_btn:
                //联网核查
                localLayout.setVisibility(View.GONE);
                MAKE_TYPE = CHEACK;
                initshell();
                break;
            case R.id.oralreportthe_lossof_btn:
                //口头挂失
                localLayout.setVisibility(View.GONE);
                selGetNumPpView.show();
                MAKE_TYPE = LOSSOF;
                break;
            case R.id.change_password_btn:
                //修改密码
                MAKE_TYPE = CHANGE_PS;
                localLayout.setVisibility(View.GONE);
                readcardtwstart();

                break;
        }
    }


    private void readcardtwstart() {
        tradeWithCards(new HttpUtils.BaseReadCardTwListener() {
            @Override
            public void onSuccess(String data, String track2Datas, String pin) {

                card_num = data;
                track2Data = track2Datas;

                cipassword = pin;
                verifycardPopupView.show();
                HttpUtilsV2.getCheckingThisBank(data, new HttpUtilsV2.NetCallBack() {
                    @Override
                    public void onSuccess(String ServerSeqNo, String ConsumerSeqNo, JSONObject rspBody) {
                        runOnUiThread(() -> {
                            verifycardPopupView.dismiss();
                            tomake();
                        });
                    }

                    @Override
                    public void onError(String code, String msg) {
                        showErr(msg);
                    }
                });
            }

            @Override
            public void onError(String msg) {
                showErr(msg);
            }
        });
    }

    /**
     * 修改密码
     */
    private void tomake() {
        showMakeHint("验证密码...");
        HttpUtilsV2.getAccountPwdVerification(card_num, cipassword,
                new HttpUtilsV2.NetCallBack() {
                    @Override
                    public void onSuccess(String ServerSeqNo, String ConsumerSeqNo, JSONObject rspBody) {
                        runOnUiThread(() -> {
                            //验证密码成功
                            dismissshowMakeHint();
                            //获取客户信息
                            showMakeHint("获取客户信息...");
                            HttpUtilsV2.getQueryBankCardInfo(card_num, new HttpUtilsV2.NetCallBack() {
                                @Override
                                public void onSuccess(String ServerSeqNo, String ConsumerSeqNo, JSONObject rspBody) {
                                    card_username = rspBody.getString("AcctName");
                                    runOnUiThread(() -> {
                                        dismissshowMakeHint();
                                        showMakeHint("黑名单验证...");
                                        HttpUtilsV2.getCheckingBankCardBlacklist(card_num, card_username, new HttpUtilsV2.NetCallBack() {
                                            @Override
                                            public void onSuccess(String ServerSeqNo, String ConsumerSeqNo, JSONObject rspBody) {
                                                runOnUiThread(() -> {
                                                    dismissshowMakeHint();
                                                    inputNewPasswordPopupView.show();
                                                });
                                            }

                                            @Override
                                            public void onError(String code, String msg) {
                                                showErr(msg);

                                            }
                                        });
                                    });
                                }

                                @Override
                                public void onError(String code, String msg) {
                                    showErr(msg);
                                }
                            });
                        });
                    }

                    @Override
                    public void onError(String code, String msg) {
                        runOnUiThread(() -> {
                            ToastUtils.showLong(msg);
                            finish();
                        });
                    }
                });
    }

    private void showErr(String msg) {
        runOnUiThread(() -> {
            errorPopup.setMsg(msg);
            errorPopupPpView.show();
        });
    }

    /**
     * 链接蓝牙机具
     */
    private void initshell() {
        mAdapter = BluetoothAdapter.getDefaultAdapter();

        if (!mAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
        c = Calendar.getInstance();
        m_sec1 = c.get(Calendar.SECOND);
        m_msec1 = c.get(Calendar.MILLISECOND);
        Set<BluetoothDevice> pairedDevices = mAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                String str;
                str = device.getName().substring(0, 3);
                Log.w("pairedDevices", "device.getName().substring(0, 1) is:" + str);
                if ((str.equalsIgnoreCase("SYN")) || (str.equalsIgnoreCase("SS-")) || (str.equalsIgnoreCase("PSB"))) {
                    Log.w("onCreate", "device.getName() is SYNTHESIS");
                    mDevice = device;
                } else   //是否能进入Else
                {
                    Log.w("onCreate", "device.getName() is not SYNTHESIS");
                    boolean bAllNum = false;
                    if (device.getName().length() > 9) {
                        str = device.getName().substring(0, 10);
                        bAllNum = str.matches("[0-9]+");
                        if (bAllNum == true) {
                            mDevice = device;
                        }
                    }
                }
                Logger.e(device.getName() + "====" + device.getAddress());
            }
            try {
                mAdapter.cancelDiscovery();

                if (mDevice != null)
                    shell = new Shell(this.getApplicationContext(), mDevice);
                c = Calendar.getInstance();
                m_sec2 = c.get(Calendar.SECOND);
                m_msec1 = c.get(Calendar.MILLISECOND);
                int d = m_sec2 - m_sec1;
                int md = m_msec2 - m_msec1;
                if (d < 0)
                    d = d + 60;
                if (md < 0)
                    md = md + 1000;
                //	mInfoView.add("connect timeee is:  "+d+"."+md+"s");

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.w("test", "Socket connect error！");
                showErr("与机具建立连接失败，请尝试重新启动应用程序!");
            }
            Log.w("test", "Socket connect OK！");
        }


        globalEnum ge = globalEnum.NONE;
        Log.w("TestJarActivity", "In ButtonInitOnClick shell 00");
        //mInfoView.add("ButtonInitOnClick");
        if (shell == null) {
            Log.w("TestJarActivity", "In ButtonInitOnClick shell is null");
            try {
                if (mDevice == null) {
                    showErr("与机具建立连接失败，请检查蓝牙配置");
                    Log.w("TestJarActivity", "In ButtonInitOnClick shell 212");
                    return;
                }
                shell = new Shell(getApplicationContext(), mDevice);
                Logger.e("TestJarActivity" + "In ButtonInitOnClick shell 11");
            } catch (Exception e) {
                Logger.e("TestJarActivity" + "In ButtonInitOnClick shell 22");
                e.printStackTrace();
            }
        }

        try {
            if (shell.Register()) {
                //0316 btnRegist.setEnabled(false);
                Toast.makeText(this, "取机具编号成功！", Toast.LENGTH_SHORT).show();
                ge = shell.Init();
                if (ge == globalEnum.INITIAL_SUCCESS) {
                    Toast.makeText(this, "建立连接成功", Toast.LENGTH_SHORT).show();
                    brushtheIdentityPpView.show();
                    new Thread(new GetDataThread()).start();
                } else {
                    shell.EndCommunication();//0316
                    localLayout.setVisibility(View.VISIBLE);
                    showErr("与机具建立连接失败，请检查蓝牙配置");
                }
            } else {
                localLayout.setVisibility(View.VISIBLE);
                showErr("与机具建立连接失败，请检查蓝牙配置");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 确认联网核查信息 点击确定
     */
    @Override
    public void SureIdInfo() {
        finish();
    }

    /**
     * 口头挂失
     * <p>
     * 选择是 手动输入 还是读卡
     *
     * @param TYPE
     */
    @Override
    public void SelGetNumType(String TYPE) {
        selGetNumPpView.dismiss();
        if (TYPE == READGET) {
            initshell();
        } else if (TYPE == HEADERGET) {
            inputIdNumNamePpView.show();
        }
    }

    /**
     * 获取用户信息
     */
    private void getUserData(String name, String userid) {
        userAccBeans = new ArrayList<>();
        Gson gson = new Gson();
        identityCard = userid;
        idusername = name;
        showMakeHint("查询账户信息...");
        HttpUtilsV2.getCustomerAccountInformationQuery(
                "A",
                userid,
                name,
                "", new HttpUtilsV2.NetCallBack() {
                    @Override
                    public void onSuccess(String ServerSeqNo, String ConsumerSeqNo, JSONObject rspBody) {
                        userAccBeans = gson.fromJson(rspBody.getString("AcctsList"),
                                new TypeToken<ArrayList<UserAccBean>>() {
                                }.getType());
                        KLog.e(userAccBeans.size() + "size");
                        runOnUiThread(() -> {
                            dismissshowMakeHint();
                            sellossOfPp.setUserAccBeans(userAccBeans);
                            sellossOfPpView.show();
                        });
                    }

                    @Override
                    public void onError(String code, String msg) {
                        showErr(msg);
                    }
                });
    }


    /**
     * 选择账户之后  点击挂失按钮之后
     *
     * @param data
     */
    @Override
    public void LossPpCall(String data) {
        lossPpView.dismiss();
        inputpasswordPopupView.show();
    }

    /**
     * 挂失
     *
     * @param password
     */
    @Override
    public void SendPassword(String password) {
        inputpasswordPopupView.dismiss();
        cipassword = HttpUtils.getResult(password, mUserAccBean.getAcctNo());
        make_time = TimeUtils.getTimeData();
        showMakeHint("正在交易...");
        HttpUtilsV2.getLostBankCard(
                mUserAccBean.getAcctNo(),
                cipassword,
                "A",
                identityCard,
                new HttpUtilsV2.NetCallBack() {
                    @Override
                    public void onSuccess(String ServerSeqNo, String ConsumerSeqNo, JSONObject rspBody) {
                        mServerSeqNo = ServerSeqNo;
                        runOnUiThread(() -> {
                            KLog.e("交易成功");
                            dismissshowMakeHint();
                            sellOSSuccessPpView.show();
                            sellOSSuccessPp.setCardnum(mUserAccBean.getAcctNo());
                            sellOSSuccessPp.setName(idusername);
                        });
                    }

                    @Override
                    public void onError(String code, String msg) {
                        showErr(msg);
                    }
                });
    }

    /**
     * 挂失成功
     */
    @Override
    public void PpCallbACK() {
        sellOSSuccessPpView.dismiss();
        surePrintPopupView.show();

    }

    @Override
    public void onSucessCallBack() {
        finish();
    }

    /**
     * 输入身份证号  姓名
     *
     * @param username
     * @param idnum
     */
    @Override
    public void NumNameCallBack(String username, String idnum) {
        inputIdNumNamePpView.dismiss();
        getUserData(username, idnum);

    }


    /**
     * 修改密码成功 点击确定
     */
    @Override
    public void onchangePwok() {
        changePsSuccessPpView.dismiss();
        surePrintPopupView.show();
    }

    /**
     * 确认打印
     */
    @Override
    public void ToPrint() {
        surePrintPopupView.dismiss();
        printingPopupView.show();
        //打印修改密码
        HttpUtilsV2.getElectronicSeal("1", new HttpUtilsV2.NetCallBack() {
            @Override
            public void onSuccess(String ServerSeqNo, String ConsumerSeqNo, JSONObject rspBody) {
                runOnUiThread(() -> {
                    if (MAKE_TYPE.equals(LOSSOF)) {
                        PrintUtil.PrintSell(
                                PosFuncs.getInstace(),
                                make_time,
                                mServerSeqNo,
                                "口头挂失",
                                idusername,
                                mUserAccBean.getAcctNo(),
                                rspBody.getString("ImgBase64"), new PrintUtil.onPrintinterface() {
                                    @Override
                                    public void success(String success) {
                                        PrintUtil.PrintSell2(
                                                PosFuncs.getInstace(),
                                                make_time,
                                                mServerSeqNo,
                                                "口头挂失",
                                                idusername,
                                                mUserAccBean.getAcctNo(),
                                                rspBody.getString("ImgBase64"), new PrintUtil.onPrintinterface() {
                                                    @Override
                                                    public void success(String success) {
                                                        SPStaticUtils.put("ccsno", SPStaticUtils.getInt("ccsno", 1) + 1);
                                                        ToastUtils.showLong(success);
                                                        finish();
                                                    }

                                                    @Override
                                                    public void failed(String error) {
                                                        showErr(error);
                                                    }
                                                });
                                    }

                                    @Override
                                    public void failed(String error) {
                                        showErr(error);
                                    }
                                });


                    } else {


                        PrintUtil.printChangePsword(
                                PosFuncs.getInstace(),
                                make_time,
                                "修改密码",
                                mServerSeqNo,
                                card_username,
                                card_num,
                                rspBody.getString("ImgBase64"), new PrintUtil.onPrintinterface() {
                                    @Override
                                    public void success(String success) {
                                        PrintUtil.printChangePsword2(
                                                PosFuncs.getInstace(),
                                                make_time,
                                                "修改密码",
                                                mServerSeqNo,
                                                card_username,
                                                card_num,
                                                rspBody.getString("ImgBase64"), new PrintUtil.onPrintinterface() {
                                                    @Override
                                                    public void success(String success) {
                                                        SPStaticUtils.put("ccsno", SPStaticUtils.getInt("ccsno", 1) + 1);
                                                        ToastUtils.showLong(success);
                                                        finish();
                                                    }

                                                    @Override
                                                    public void failed(String error) {
                                                        showErr(error);
                                                    }
                                                });
                                    }

                                    @Override
                                    public void failed(String error) {
                                        showErr(error);
                                    }
                                });
                    }
                });
            }

            @Override
            public void onError(String code, String msg) {
                showErr(msg);
            }
        });

    }

    @Override
    public void finished() {
        finish();
    }

    /**
     * 输入新密码完成
     *
     * @param pw
     */
    @Override
    public void newPsCall(String pw) {
        String newps = HttpUtils.getResult(pw, card_num);
        inputNewPasswordPopupView.dismiss();
        dealingPopupView.show();
        make_time = TimeUtils.getTimeData();
        HttpUtilsV2.getChangePassword(
                card_num,
                cipassword,
                newps,
                "",
                "",
                "",
                "",
                track2Data, new HttpUtilsV2.NetCallBack() {
                    @Override
                    public void onSuccess(String ServerSeqNo, String ConsumerSeqNo, JSONObject rspBody) {
                        mServerSeqNo = ServerSeqNo;

                        runOnUiThread(() -> {
                            dealingPopupView.dismiss();
                            changePsSuccessPp.setmCardnum(card_num);
                            changePsSuccessPp.setmName("修改密码");
                            changePsSuccessPp.setmUsername(card_username);
                            changePsSuccessPpView.show();
                        });

                    }

                    @Override
                    public void onError(String code, String msg) {
                        showErr(msg);
                    }
                });

    }

    /**
     * 确认读取的身份信息
     */
    @Override
    public void dinfoCall() {
        sureIdInfoPpView.dismiss();
        dealingPopupView.show();

        HttpUtilsV2.getNetworkVerification(userid, username, new HttpUtilsV2.NetCallBack() {
            @Override
            public void onSuccess(String ServerSeqNo, String ConsumerSeqNo, JSONObject rspBody) {
                String checkresult = rspBody.getString("checkresult");
                String checkresultdata = "";
                if (checkresult.equals("00")) {
                    checkresultdata = ("公民身份证号码与姓名一致\n且存在照片");
                } else if (checkresult.equals("01")) {
                    checkresultdata = ("公民身份证号码与姓名一致\n但不存在照片");
                } else if (checkresult.equals("02")) {
                    checkresultdata = ("公民身号码存在 \n但姓名不匹配");
                } else if (checkresult.equals("03")) {
                    checkresultdata = ("公民身份号码不存在");
                } else if (checkresult.equals("04")) {
                    checkresultdata = ("其他错误");
                } else if (checkresult.equals("05")) {
                    checkresultdata = ("输入的参数错误");
                } else if (checkresult.equals("06")) {
                    checkresultdata = ("联网核查公民身份系统故障");
                } else if (checkresult.equals("07")) {
                    checkresultdata = ("所选身份证件类型没有公民身份号码");
                }


                String photo = rspBody.getString("photo");
                KLog.e(photo + "photo");
                String finalCheckresultdata = checkresultdata;
                runOnUiThread(() -> {
                    idInfoPp.setmInfoName(username);
                    idInfoPp.setmInfoJg(finalCheckresultdata);
                    idInfoPp.setmInfoId(userid);
                    idInfoPp.setmIdImg(photo);
                    idInfoPpView.show();
                });
            }

            @Override
            public void onError(String code, String msg) {
                showErr(msg);
            }
        });

    }

    @Override
    public void seLLCallData(UserAccBean userAccBean) {
        mUserAccBean = userAccBean;
        sellossOfPpView.dismiss();
        inputpasswordPopupView.show();
    }


    /**
     * 开启线程
     */
    private class GetDataThread implements Runnable {
        private String data;
        private byte[] cardInfo = new byte[256];
        private int count = 0;
        private Message msg;//主要改了这个地方，好像启作用了
        private String wltPath = "";
        private String termBPath = "";
        private boolean bRet = false;


        public GetDataThread() {
        }

        public void run() {
            globalEnum ge = globalEnum.GetIndentiyCardData_GetData_Failed;
            try {
                Thread.sleep(2000);

                globalEnum gFindCard = globalEnum.NONE;
                long start = System.currentTimeMillis();
                while (!bStop) {
                    data = null;//
                    msg = handler.obtainMessage(71, data);//发送消息
                    handler.sendMessage(msg);
                    bRet = shell.SearchCard();
                    if (bRet) {
                        data = null;//
                        msg = handler.obtainMessage(1, data);//发送消息
                        handler.sendMessage(msg);
                        bRet = shell.SelectCard();
                        if (bRet) {
                            data = null;//
                            msg = handler.obtainMessage(2, data);//发送消息
                            handler.sendMessage(msg);
                            //Thread.sleep(100);

                            int nRet = shell.ReadCardWithFinger();//nRet 1:二代证无指纹 2：二代证包含指纹
                            if (nRet > 0) {
                                data = null;//
                                byte[] fingerBuff = new byte[1024];
                                byte[] wltBuff = new byte[1024];
                                if (nRet == 2) {
                                    bRet = shell.GetFingerData(fingerBuff);
                                    //	Log.w("ComShell","fingerData is:"+Util.toHexStringNoSpace(fingerBuff, 1024));
                                }

                                msg = handler.obtainMessage(3, data);//发送消息
                                handler.sendMessage(msg);

                                cardInfo = shell.GetCardInfoBytes();
                                if (shell.GetCardTypeFlag(cardInfo) == 0) {//0时为二代证信息
                                    data = String.format(
                                            "姓名：%s 性别：%s 民族：%s 出生日期：%s 住址：%s 身份证号：%s 签发机关：%s 有效期：%s-%s",
                                            shell.GetName(cardInfo), shell.GetGender(cardInfo), shell.GetNational(cardInfo),
                                            shell.GetBirthday(cardInfo), shell.GetAddress(cardInfo),
                                            shell.GetIndentityCard(cardInfo), shell.GetIssued(cardInfo),
                                            shell.GetStartDate(cardInfo), shell.GetEndDate(cardInfo));
                                    if (nRet == 2) {
                                        data = data + "\r\n" + "";
                                    } else if (nRet == 1) {
                                        data = data + "\r\n" + "";
                                    }
                                    //拿到识别的身份证 和姓名
                                    //拿到识别的身份证 和姓名
                                    //拿到识别的身份证 和姓名
                                    //拿到识别的身份证 和姓名
                                    //拿到识别的身份证 和姓名
                                    //拿到识别的身份证 和姓名

                                    sf_name = shell.GetName(cardInfo);
                                    sf_num = shell.GetIndentityCard(cardInfo);
                                    if (MAKE_TYPE == LOSSOF) {
                                        //如果是挂失操作
                                        String[] iddata = data.split(" ");
                                        String name = iddata[0].split("：")[1];
                                        String id = iddata[5].split("：")[1];
                                        runOnUiThread(() -> {
                                            brushtheIdentityPpView.dismiss();
                                        });
                                        getUserData(name, id);
                                    } else if (MAKE_TYPE == CHEACK) {
                                        msg = handler.obtainMessage(0, data);//发送消息
                                        handler.sendMessage(msg);
                                    }
                                    //拿到识别的身份证 和姓名
                                    //拿到识别的身份证 和姓名
                                    //拿到识别的身份证 和姓名
                                    //拿到识别的身份证 和姓名
                                    //拿到识别的身份证 和姓名
                                    //拿到识别的身份证 和姓名
                                } else if (shell.GetCardTypeFlag(cardInfo) == 1) {//1时为外国人居住证信息
                                    data = String.format(
                                            "英文名字：%s 中文名字：%s 性别：%s 国籍代码：%s 国籍名称：%s 出生日期：%s 身份证号：%s 签发机关：%s 有效期：%s-%s",
                                            shell.GetFEName(cardInfo),
                                            shell.GetFCName(cardInfo),
                                            shell.GetFGender(cardInfo),
                                            shell.GetFCountryCode(cardInfo),
                                            shell.GetFCountryName(cardInfo),
                                            shell.GetFBirthday(cardInfo),
                                            shell.GetFIndentityCard(cardInfo),
                                            shell.GetFIssued(cardInfo),
                                            shell.GetFStartDate(cardInfo),
                                            shell.GetFEndDate(cardInfo));
                                    if (nRet == 2) {
                                        data = data + "\r\n" + "指纹特征值已读取";
                                    } else if (nRet == 1) {
                                        data = data + "\r\n" + "不包含指纹";
                                    }
                                } else {
                                    msg = handler.obtainMessage(6, data);//读卡失败
                                    handler.sendMessage(msg);    //readC
                                    break;
                                }


                                //	Log.w("777"," shell.GetEndDate(cardInfo) is:"+ shell.GetEndDate(cardInfo));
                                byte[] bmpBuff = new byte[38862];
                                boolean bRet = shell.GetWltData(wltBuff);
                                if (bRet) {
                                    Log.w("ComShell", "packageName is :" + packageName);
                                    nRet = shell.GetPicByBuff(packageName, wltBuff, bmpBuff);
                                    Log.w("ComShell", "GetPicByBuff nRet is:" + nRet);
                                    if (nRet == 1) {
                                        Bitmap bm = BitmapFactory.decodeByteArray(
                                                bmpBuff, 0, 38862);
                                        if (bm != null) {
                                            msg = handler.obtainMessage(100, bm);//发送消息
                                            handler.sendMessage(msg);
                                        }
                                    } else if (nRet == -5) {
                                        msg = handler.obtainMessage(101, data);//发送消息
                                        handler.sendMessage(msg);
                                    } else if (nRet == -1) {
                                        msg = handler.obtainMessage(102, data);//发送消息
                                        handler.sendMessage(msg);
                                    }
                                    //break;//0316  调试用，所以增加
                                }
                            } else {
                                msg = handler.obtainMessage(6, data);//发送消息
                                handler.sendMessage(msg);    //readCard error
                            }
                        } else {
                            msg = handler.obtainMessage(5, data);//发送消息
                            handler.sendMessage(msg);    //selectCard error
                        }
                    } else {
                        msg = handler.obtainMessage(4, data);//发送消息
                        handler.sendMessage(msg);    //searchCard error
                    }
                    Thread.sleep(50);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler() {//处理UI绘制
        private String data;
        private Bitmap bm;
        private int t_sec1, t_sec2;
        private int t_msec1, t_msec2;

        private Calendar t;

        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {//M_ERROR  M_VALIDATE_ERROR I_ERROR I_VALIDATE_ERROR
            switch (msg.what) {                    //C_ERROR  C_VALIDATE_ERROR D_ERROR D_VALIDATE_ERROR
                case 0:
                    data = (String) msg.obj;
                    if (data == null) {
                    } else {
                        //mInfoView.clear();
                        t = Calendar.getInstance();
                        t_sec2 = t.get(Calendar.SECOND);
                        t_msec2 = t.get(Calendar.MILLISECOND);
                        int d = t_sec2 - t_sec1;
                        int md = t_msec2 - t_msec1;
                        if (d < 0)
                            d = d + 60;
                        if (md < 0) {
                            d = d - 1;
                            md = md + 1000;
                        }
                        KLog.e(data);
                        String[] iddata = data.split(" ");
                        KLog.e(iddata.length + "lenght");
                        KLog.e(iddata[0]);
                        KLog.e(iddata[7].split("：")[1]);
                        userid = iddata[5].split("：")[1];
                        username = iddata[0].split("：")[1];
                        brushtheIdentityPpView.dismiss();

                        sureIdInfoPp.setAdresss(iddata[4].split("：")[1]);
                        sureIdInfoPp.setNames(iddata[0].split("：")[1]);
                        sureIdInfoPp.setBirths(iddata[3].split("：")[1]);
                        sureIdInfoPp.setSexs(iddata[1].split("：")[1]);
                        sureIdInfoPp.setValidtimes(iddata[7].split("：")[1].trim());
                        sureIdInfoPp.setNations(iddata[2].split("：")[1]);
                        sureIdInfoPp.setVisas(iddata[6].split("：")[1]);

                        sureIdInfoPpView.show();
                    }
                    break;
                case 71:
                    t = Calendar.getInstance();
                    t_sec1 = t.get(Calendar.SECOND);
                    t_msec1 = t.get(Calendar.MILLISECOND);
                    break;
                case 100:

                    //  deleteFile("zp.bmp");

                    break;
                case 101:
                    Toast.makeText(SpecialBusinessActivity.this, "照片解码授权文件不正确", Toast.LENGTH_SHORT).show();
                    break;
                case 102:
                    Toast.makeText(SpecialBusinessActivity.this, "照片原始数据不正确", Toast.LENGTH_SHORT).show();


                    break;
                case 1:


                    //mInfoView.add("SearchCard ok");
                    break;
                case 4:
//			mInfoView.clear();
//			mInfoView.add("SearchCard error");
                    //mInfoView.add("正在寻卡...");
                    break;
                case 5:
                    Toast.makeText(SpecialBusinessActivity.this, "SelectCard error", Toast.LENGTH_SHORT).show();

                    break;
                case 6:
                    Toast.makeText(SpecialBusinessActivity.this, "ReadCard error", Toast.LENGTH_SHORT).show();
                    break;
                case 87:
                    Toast.makeText(SpecialBusinessActivity.this, "读卡初始化中，请稍候...", Toast.LENGTH_SHORT).show();
                    break;
                case 88:
                    Toast.makeText(SpecialBusinessActivity.this, "机具信息监听中...", Toast.LENGTH_SHORT).show();
                    break;
                case 99:
                    break;
                default:
                    break;
            }
        }
    };


}
